package com.example.util;

import com.alibaba.fastjson.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public abstract class BaseServlet extends HttpServlet {
    public abstract Class<?> getServletClass();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        try {
            Method method = getServletClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            Object o = getServletClass().newInstance();
            Object invoke = method.invoke(o, req, resp);
            if (invoke instanceof String){
                String string = invoke.toString();
                req.getRequestDispatcher(string+".jsp").forward(req,resp);
            }else{
                BackContent backContent=(BackContent) invoke;
                String jsonString = JSONArray.toJSONString(backContent);
                PrintWriter writer=resp.getWriter();
                writer.print(jsonString);
                writer.flush();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
